package co.mobiless.noterecorder;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import co.mobiless.noterecorder.activities.EditRecord;
import co.mobiless.noterecorder.activities.VerGrabacion;
import co.mobiless.noterecorder.utilities.GrabacionesCursorAdapter;
import co.mobiless.noterecorder.utilities.SmilDataSet;
import co.mobiless.noterecorder.utilities.SmilRegion;
import co.mobiless.noterecorder.utilities.SmilResource;
import co.mobiless.noterecorder.utilities.SmilXmlGenerator;

public class ListaGrabaciones extends ListActivity {
	private StorageData db;
	public static final int VER_GRABACION = Menu.FIRST;
	public static final int EXPORTAR_GRABACION = Menu.FIRST+1;
	public static final int EDITAR_GRABACION = Menu.FIRST+2;
	public static final int VER_NOTAS = Menu.FIRST+3;
	public static final int NUEVA_GRABACION = Menu.FIRST+4;
	public static final int BORRAR_GRABACION = Menu.FIRST+5;
	private Cursor mGrabacionesCursor;
	private static final int RECORD_EDIT=1;
	private static SmilDataSet mEditingDataSet;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.lista_grabaciones);
        setTitle(R.string.titulo_lista_grabaciones);
        db = new StorageData(this);
        db.open();
        manejarIntent(getIntent());
		registerForContextMenu(getListView());
    }
    
    private void manejarIntent(Intent intent){
    	if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            fillData(query);
        } else{
        	fillData("");
        }
    	
    }

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		manejarIntent(intent);
	}



	private void fillData(String q) {
        // Get all of the records from the database and create the item list
		mGrabacionesCursor = db.fetchAllGrabaciones(q);
		
        startManagingCursor(mGrabacionesCursor);
        
        String[] from = new String[] { StorageData.KEY_ROW_TITLE_RECORD,StorageData.KEY_ROW_LENGHT_RECORD, StorageData.KEY_ROW_DATE_RECORD, StorageData.KEY_ROW_CATEGORY_RECORD };        
        //Log.d("from", "" + from.length);
        int[] to = new int[] { R.id.tituloGrabacion, R.id.duracionGrabacion, R.id.fechaGrabacion, R.id.categoria};
        
        // Now create an array adapter and set it to display using our row
        //SimpleCursorAdapter records = new SimpleCursorAdapter(this, R.layout.fila_grabaciones, mGrabacionesCursor, from, to);
        GrabacionesCursorAdapter records = new GrabacionesCursorAdapter(this, R.layout.fila_grabaciones, mGrabacionesCursor, from, to);
        setListAdapter(records);
    }	
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, NUEVA_GRABACION, 0, R.string.nuevaGrabacion);
		return result;
	}
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case NUEVA_GRABACION:
                nuevaGrabacion();
                return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle(R.string.tituloMenuGrabacion);
        //menu.add(0, VER_GRABACION, 0, R.string.verGrabacion);
        menu.add(0, EXPORTAR_GRABACION, 0, R.string.exportarGrabacion);
        menu.add(0, EDITAR_GRABACION, 1, R.string.editarGrabacion);
		menu.add(0, VER_NOTAS, 2, R.string.verNotas);
		menu.add(0, BORRAR_GRABACION, 3, R.string.borrarGrabacion);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info;
    	Cursor c = mGrabacionesCursor;
    	String pathXMLFile = c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LOCATION_AUDIO_RECORD));
    	//Log.d("path para el XML: ",pathXMLFile );
    	final String pathRecordArchive= c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LOCATION_AUDIO_RECORD));
    	//final String pathRecordArchive= c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LOCATION_AUDIO_RECORD))+"/"+
        //c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_ARCHIVE_AUDIO_RECORD));
    	String nameArchiveRecord = c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_ARCHIVE_AUDIO_RECORD));
        switch(item.getItemId()) {
        	/*        	case VER_GRABACION:
        		info = (AdapterContextMenuInfo) item.getMenuInfo();
                //c = mGrabacionesCursor;
                String idGrab1 = Long.toString(info.id);
                verGrabacion(idGrab1);
        		return true;*/
            case EDITAR_GRABACION:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                //c = mGrabacionesCursor;
                //c.moveToPosition(info.position);
                Intent i = new Intent(this, EditRecord.class);
                i.putExtra(StorageData.KEY_ROWID, info.id);
                //i.putExtra(StorageData.KEY_ROW_TITLE_RECORD, c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_TITLE_RECORD)));
                //i.putExtra(StorageData.KEY_ROW_DESC_RECORD, c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_DESC_RECORD)));
                //i.putExtra(StorageData.KEY_ROW_CATEGORY_RECORD, c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_CATEGORY_RECORD)));
                startActivityForResult(i, RECORD_EDIT);
                
                //fillData();
                return true;
            case VER_NOTAS:
            	info = (AdapterContextMenuInfo) item.getMenuInfo();
                //c = mGrabacionesCursor;
                String idGrab = Long.toString(info.id);
                verNotasAsociadas(idGrab);
                //fillData();
                return true;
            case BORRAR_GRABACION:
            	info = (AdapterContextMenuInfo) item.getMenuInfo();
            	
            	//Obtener la ubicaci�n del archivo de audio
            	//c = mGrabacionesCursor;
                c.moveToPosition(info.position);
                //pathRecordArchive = c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LOCATION_AUDIO_RECORD))+"/"+
                //c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_ARCHIVE_AUDIO_RECORD));
                
                Log.d("pathRecord", pathRecordArchive);
            	final long idRec = info.id;
            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
            	builder.setMessage("Esta seguro de borrar la grabacion y todas sus notas?")
            	       .setCancelable(false)
            	       .setPositiveButton("Si", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   db.deleteRecord(idRec, pathRecordArchive);
            	        	   Context context = getApplicationContext();
            	               Toast.makeText(context, "Grabacion borrada" , Toast.LENGTH_SHORT).show();
            	        	   fillData("");
            	           }
            	       })
            	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	                dialog.cancel();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	builder.show();
            	fillData("");
                return true;
            case EXPORTAR_GRABACION:
            	mEditingDataSet = new SmilDataSet();
            	info = (AdapterContextMenuInfo) item.getMenuInfo();
            	//TODO: acomodar el tama�o de la regi�n dependiendo de las im�genes
            	SmilRegion region = new SmilRegion("region","#000000", 0, 0, 800,447 );
            	c.moveToPosition(info.position);
            	String nombreGrab = c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_TITLE_RECORD));
            	nombreGrab = SmilXmlGenerator.remove1(nombreGrab);
            	//crea el recurso del archivo de grabaci�n
            	
            	SmilResource res = new SmilResource(nombreGrab, nameArchiveRecord, region, 0, 
            			Integer.parseInt(c.getString(c.getColumnIndexOrThrow(StorageData.KEY_ROW_LENGHT_RECORD))), "audio");
            	
            	//TODO: almacenar categor�a, nombre y descripci�n de la grabaci�n para ponerlos en el XML
            	mEditingDataSet.addResource(res);
            	
            	long idRecord = info.id;
            	
            	//Crear un recurso por cada nota
            	Cursor notas = db.fetchAllNotas("",(int) idRecord);
            	if (notas.moveToFirst()) {
       		     //Recorremos el cursor hasta que no haya m�s registros
	       			Integer id;
	       			String nameNote;
            		String textoAd;
            		int beginTime;
            		int endTime;
	       		     do {
	       		          id = notas.getInt(0);
	       		          nameNote = notas.getString(1);
	       		          beginTime = Integer.parseInt(notas.getString(2))/1000;
	       		          endTime = (Integer.parseInt(notas.getString(2))/1000)+(Integer.parseInt(notas.getString(3))/1000);
	       		          textoAd = notas.getString(4);
	       		          String nombreImg = notas.getString(notas.getColumnIndexOrThrow(StorageData.KEY_ROW_NAME_ARCHIVE_IMAGE_NOTE));
	       		          res = new SmilResource(nameNote, pathXMLFile, region, beginTime, endTime, "img", textoAd, "desc"+nameNote, nombreImg);
	       		          mEditingDataSet.addResource(res);
	       		     } while(notas.moveToNext());
	       		}
            	notas.close();
            	try {
            		SmilXmlGenerator.saveAsXML(mEditingDataSet, nombreGrab, pathXMLFile);
            	} catch (Exception e) { // display exception dialog box
        			Log.d("generacion XML","Cannot save file.");
            	}
				try {
					zipFolder(pathXMLFile, "/mnt/sdcard/NoteRecorder/"+nombreGrab+".zip");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Intent sharingIntent = new Intent(Intent.ACTION_SEND);
				Uri zipUri = Uri.parse("file:///sdcard/NoteRecorder/"+nombreGrab+".zip");

				sharingIntent.setType("application/zip");
				sharingIntent.putExtra(Intent.EXTRA_STREAM, zipUri);
				startActivity(Intent.createChooser(sharingIntent, "Compartir grabacion usando.."));
			/*TODO: Borrar los archivos .smil y .zip
			 * File file = new
			 * File("/mnt/sdcard/NoteRecorder/"+nombreGrab+".zip");
			 * file.delete(); file = new
			 * File(pathXMLFile+"/"+nombreGrab+".smil"); file.delete();
			 */
				fillData("");
                return true;
        }
        return super.onContextItemSelected(item);
    }

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		db.close();
		super.onDestroy();
	}

	/* 	private void buscaGrabaciones(String query) {
		// TODO: crear m�todo para b�squeda de grabaciones filtradas
		
	} */

	private void verNotasAsociadas(String idGrabacion) {
		Intent i = new Intent(this, ListaNotas.class);
		i.putExtra("idGrabacion", idGrabacion);
		startActivity(i);
		
	}
	

	private void nuevaGrabacion() {
		Intent i = new Intent(this, NoteRecorder.class);
        //startActivityForResult(i, ACTIVITY_CREATE);
		startActivity(i);
		this.finish();
	} 
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //Bundle extras = intent.getExtras();
        switch(requestCode) {
            case RECORD_EDIT:
            	if(resultCode==-1){//se puls� el bot�n guardar
	                /*Long rowId = extras.getLong(StorageData.KEY_ROWID);
	                if (rowId != null) {
	                    String editTitle = extras.getString(StorageData.KEY_ROW_TITLE_RECORD);
	                    String editDesc = extras.getString(StorageData.KEY_ROW_DESC_RECORD);
	                    String editCat = extras.getString(StorageData.KEY_ROW_CATEGORY_RECORD);
	                    if(db.updateRecord(rowId, editTitle, editDesc, editCat)){
	                    	Toast.makeText(this,"Grabaci�n actualizada correctamente",2).show();
	                    }else{
	                    	Toast.makeText(this,"No se pudo actualizar la grabaci�n",2).show();
	                    }
	                }*/
	                fillData("");
            	}else{ //se puls� el bot�n cancelar
            		
            	}
                break;
        }
    }
	
    /*TODO: Cuando se le da un click, abre la grabaci�n
     * 
     *     @Override
     */
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	//Log.d("Id Grabación: ",Long.toString(id));
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, VerGrabacion.class);
		i.putExtra("idGrabacion", Long.toString(id));
		startActivity(i);
    }
	
	/*	private void verGrabacion(String idGrabacion) {
		Intent i = new Intent(this, VerGrabacion.class);
		i.putExtra("idGrabacion", idGrabacion);
		startActivity(i);
		
	}*/
	
	static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
	    ZipOutputStream zip = null;
	    FileOutputStream fileWriter = null;

	    fileWriter = new FileOutputStream(destZipFile);
	    zip = new ZipOutputStream(fileWriter);

	    addFolderToZip("", srcFolder, zip);
	    zip.flush();
	    zip.close();
	  }

	  static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
	      throws Exception {

	    File folder = new File(srcFile);
	    if (folder.isDirectory()) {
	      addFolderToZip(path, srcFile, zip);
	    } else {
	      byte[] buf = new byte[1024];
	      int len;
	      FileInputStream in = new FileInputStream(srcFile);
	      zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
	      while ((len = in.read(buf)) > 0) {
	        zip.write(buf, 0, len);
	      }
	    }
	  }

	  static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
	  throws Exception {
	    File folder = new File(srcFolder);

	    for (String fileName : folder.list()) {
	      if (path.equals("")) {
	        addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
	      } else {
	        addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
	      }
	    }
	  }

	
}
